package com.ch.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cj-ch
 * @date 2018/4/17 上午8:40
 */
public class AccessFilter extends ZuulFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 过滤器的类型,它决定过滤器在请求的哪个生命周期中执行.这里定义为Pre代表请求被路由之前执行.
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断该过滤器是否需要执行
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体执行逻辑
     * @return
     */
    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        logger.info("send {} request to {}",request.getMethod(),request.getRequestURL().toString());
        String accessToken = request.getParameter("accessToken");
        if(StringUtils.isEmpty(accessToken)){
            logger.warn("accessToken is blank");
            context.getResponse().setCharacterEncoding("utf-8");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.setResponseBody("校验失败");
            return  null;
        }
        logger.info("access is ok");
        return null;
    }
}
